package com.cn.zy;

import org.junit.Test;
import sun.misc.RequestProcessor;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zhangyi
 * @date 2019/1/21 17:52
 */
public class ReadWriteTest {
    private Lock lock = new ReentrantLock();
    private ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();
    private Lock readLock = rwlock.readLock();
    private Lock writeLock = rwlock.writeLock();
    private int value;

    public Object handlerRead(Lock lock){
        try {
            lock.lock();
            Thread.sleep(1000);
            return value;
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        return null;
    }

    public void handleWrite(Lock lock,int index){
        try{
            lock.lock();
            Thread.sleep(100);
            value = index;
            System.out.println(value);
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    @Test
    public void readWriter() throws InterruptedException {
        ReadWriteTest readWriteTest = new ReadWriteTest();
        Runnable read = new Runnable() {
            @Override
            public void run() {
                readWriteTest.handlerRead(readLock);
//                readWriteTest.handlerRead(lock);
            }
        };
        Runnable write = new Runnable() {
            @Override
            public void run() {
                readWriteTest.handleWrite(writeLock,new Random(10).nextInt());
//                readWriteTest.handleWrite(lock,new Random(100).nextInt());
            }
        };
        for(int i = 0 ; i < 10; i++){
            new Thread(read).start();
        }
        for(int i = 0 ; i < 10; i++){
            new Thread(write).start();
        }
    }
}
